import pandas as pd
import numpy as np
from sklearn.impute import SimpleImputer


# # 使用fit_transform修改NaN值
# imputer = SimpleImputer(missing_values=np.nan, strategy='constant', fill_value=12)
# data = {'A': ['x', 'y', 'z'], 'B': [10.0, np.nan, 30.12], 'C': [10, 20, 30]}
# df = pd.DataFrame(data=data)
# print(df)
# # print(type(df['A']), type(df[['A']]))
# df[['B']] = imputer.fit_transform(df[['B']])  # fit_transform参数要二维, 要传列表(返回DataFrame), 只传一个列而且不是在列表里的会返回Series
# print(df)

# # 筛选某列中没有空值的行
# data = {'A': ['x', 'y', 'z'], 'B': [10.0, np.nan, 30.12], 'C': [10, 20, 30]}
# df = pd.DataFrame(data)
# df = df[df['B'].notnull()].reset_index(drop=True)
# print(df)

# 对多列的数据用同一种方法修改NaN值
# 如: 对字符串型的修改为empty
data = {
    'A': [np.nan, 1, 2],
    'B': [10.0, np.nan, 30.12],
    'C': [10, 20, 30],
    'D': ['r', np.nan, np.nan]
        }
df = pd.DataFrame(data)
print(df.info())
imputer = SimpleImputer(missing_values=np.nan, strategy='constant', fill_value='empty')
str_col = df.select_dtypes('object').columns  # 多个类型都要的话传列表
# print(str_col)
print(df)
print('='*30)
df.loc[:, str_col] = imputer.fit_transform(df[str_col])
print(df)
